import { Plugin, Context } from '@nuxt/types';
import { message } from 'ant-design-vue';
import { NuxtAxiosInstance } from '@nuxtjs/axios';

interface IAxiosContext extends Context {
  $axios: NuxtAxiosInstance;
}

const axiosPlugin: Plugin = (ctx: IAxiosContext) => {
  let axios: NuxtAxiosInstance  = ctx.$axios;

  axios.defaults.timeout = 10000;

  axios.interceptors.request.use(
    config => {
      if (ctx.store && ctx.store.getters['user/loggedIn']) {
        const currentUser = ctx.store.state.user.userInfo;
        if (currentUser && currentUser.tokenHeader && currentUser.token) {
          config.headers[currentUser.tokenHeader] = currentUser.token;
        }
      }
      return config;
    },
    err => {
      return Promise.reject(err);
    },
  );


  axios.interceptors.response.use(
    res => {
      const result = res.data;
      if (result) {
        switch (result.code) {
          case 0:
            return Promise.resolve(result.data);
          case -2:
            message.warning(result.message);
            break;
          case -3:
            message.error(result.message);
            break;
          default:
            break;
        }
      }
      return Promise.resolve();
    },
    err => {
      const data = err.response.data;
      const code = err.response.status;

      if (code) {
        switch (code) {
          case 401:
            message.error('登录信息失效，请重新登录');
            break;
        }
      }
      return Promise.reject(data);
    }
  );
};

export default axiosPlugin;
